<?php
/**
 * Created by PhpStorm.
 * User: bzg
 * Date: 2019/12/4
 * Time: 14:23
 */

namespace App\Extend\SysExtend\Session;


use App\Extend\SysExtend\Cache\Cache;
use App\Extend\SysExtend\Helper;

class Session
{
    private $session_data;
    private $session_id;

    public function __construct()
    {
        $this->session_id = Helper::request()->getCookieParams('SESSIONID');
        if(!$this->session_id)
            $this->session_data = null;
        else
            $this->session_data = Cache::get($this->session_id);
    }

    /**
     * 获取session的值，支持点语法
     * @param string $name
     * @return null
     */
    public function get(string $name)
    {
        if(empty($this->session_data)) return null;
        $name_arr = explode('.',$name);
        $res = $this->session_data;
        foreach ($name_arr as $k) {
            $res = $res[$k] ?? null;
            if($res == null) {
                return null;
            }
        }
        return $res;
    }

    /**
     * 写入session
     * @param string $name
     * @param $value
     */
    public function set(string $name, $value)
    {
        $name_arr = explode('.',$name);
        $cur = &$this->session_data;
        foreach ($name_arr as $index => $k) {
            if(!isset($cur[$k])) {
                $cur[$k] = null;
            }
            $cur = &$cur[$k];
            if(!isset($name_arr[$index + 1])) {
                $cur = $value;
            }
        }
        // 写入缓存
        Cache::set($this->session_id,$this->session_data);
    }


    /**
     * 清空session
     */
    public function clear()
    {
        Cache::set($this->session_id,[]);
    }

    public static function __callStatic($name, $params)
    {
        return (new self())->$name(... $params);
    }
}